#!/usr/bin/env python
"""
A quick script to install into your `Application Support/BBEdit/Scripts` folder.
This runs Pylint (requires Pylint to be installed at `/usr/local/bin` 
so that they show up in BBEdit's search results / error / warnings window. Then
the errors can be stepped through one at a time.

A Pylint summary report is created in the new window (Unix script output).

I've bound this to control-shift-L. You must save your Python file first before
running the check.
"""
from __future__ import print_function
import os
import re
import sys
from subprocess import Popen, PIPE

PYLINT = "/usr/local/bin/pylint"

def main():
    """
        main function
    """
    try:
        doc_file = os.environ['BB_DOC_PATH']
    except KeyError:
        print('BB_DOC_PATH not found, maybe your file is not yet saved.', \
                file=sys.stderr)
        sys.exit(1)

    out, err = Popen([PYLINT, doc_file], stdout=PIPE, stderr=PIPE).communicate()
    if out:
        output = out
    else:
        output = err

    if not output:
        sys.exit(0)

    line_format = \
        re.compile('(?P<msgtype>^(R|C|W|E|F)):\s*(?P<linenr>\d+):\s*(?P<message>.*$)')
    in_report = False
    for line in output.splitlines():
        m_line = line_format.match(line)
        if m_line:
            groups = m_line.groupdict()
            print('''  File "%s", line %s, ''' % (doc_file, groups['linenr']), \
                    file=sys.stderr)
            print(groups['msgtype'] + ': ' + groups['message'], file=sys.stderr)
            continue

        if in_report:
            print(line, file=sys.stdout)
            continue        
        if line.startswith('Report'):
            print(doc_file + '\n\n' + line , file=sys.stdout)
            in_report = True
    
    sys.exit(1)

if __name__ == '__main__':
    main()
